from nicegui import ui, app

import orm
from tools.search import Search
from tools.loginout import logout
from orm import manager
from pages.page_structure import init_page


def add_user_to_group(user_id, group_id):
    succ, res = manager.add_user_to_group(group_id, user_id)
    ui.notify(res)


def remove_user_from_group(user, user_group):
    succ, res = manager.remove_user(user.id, user_group.id)
    ui.notify(res)


@ui.page("/user_group/{gid}")
async def user_group_page(gid: str):
    init_page()
    user_group = manager.get_usergroup_by_groupid(int(gid))[0]
    with ui.row():
        ui.label(user_group.group_name).classes('tracking-wide text-2xl py-8 text-black')

        if manager.is_administrator(app.storage.user.get('username')) or \
                manager.get_user(app.storage.user.get('username')).id == user_group.creator_id.id:
            def remove_group(group):
                succ, res = manager.remove_usergroup(group.id)
                ui.open("/user_groups")
                ui.notify(res)

            ui.button("解散用户组", icon="group_remove", on_click=lambda: remove_group(user_group),
                      color='text-indigo-700') \
                .classes("my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")
        else:
            def exit_group(user, user_group):
                remove_user_from_group(user, user_group)
                ui.open("/user_groups")

            ui.button("退出用户组", icon="person_remove", on_click=lambda: exit_group(user, user_group),
                      color='text-indigo-700') \
                .classes("my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")

    def on_click_question_group(question_group):
        ui.open("/question_group/{}".format(question_group.id))

    users = manager.get_users_by_groupid(user_group.group_name)
    with ui.card().classes("mx-auto w-full bg-gradient-to-br from-purple-50 to-blue-50"):
        with ui.column().classes('w-full grow'):
            with ui.row().classes('mx-auto'):
                ui.label("用户组成员").classes('my-auto mx-auto tracking-wide text-1xl text-black')
                if manager.is_administrator(app.storage.user.get('username')) or \
                        manager.get_user(app.storage.user.get('username')).id == user_group.creator_id.id:

                    def search_and_add_user_to_group(user_group):
                        def search_input(value):
                            def add_user(user, user_group):
                                add_user_to_group(user.id, user_group.id)
                                ui.open("/user_group/{}".format(user_group.id))

                            users = manager.searchUser(value)
                            with search_result:
                                search_result.clear()
                                for user in users:
                                    with ui.row().classes("w-full px=[20px]"):
                                        ui.label(user.username).classes("mx-auto grow text-center")
                                        ui.button("添加用户", on_click=lambda user=user: add_user(user, user_group)
                                                  , color='text-indigo-700', icon='person_add') \
                                            .classes('bg-gradient-to-br from-purple-200 to-blue-200 grow')

                        with ui.dialog() as dialog_search, ui.card().tight().classes('w-[400px] h-[400px]'):
                            ui.input("搜索用户名", on_change=lambda e: search_input(e.value)).classes(
                                "w-full text-indigo-700")
                            search_result = ui.card().classes("w-full h-full")
                        dialog_search.open()
                        search_input("")

                    ui.button("添加用户成员", icon="person_add",
                              on_click=lambda: search_and_add_user_to_group(user_group),
                              color='text-indigo-700') \
                        .classes("my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")

            if manager.is_administrator(app.storage.user.get('username')) or \
                    manager.get_user(app.storage.user.get('username')).id == user_group.creator_id.id:
                with ui.row().classes('w-full'):
                    ui.label("用户名").classes('text-center grow')
                    ui.label("操作").classes('text-center grow')

                def remove_user(user, user_group):
                    remove_user_from_group(user, user_group)
                    ui.open("/user_group/{}".format(user_group.id))

                for user in users:
                    with ui.card().classes("h-fit w-full bg-gradient-to-br from-blue-50 to-purple-50"):
                        with ui.row().classes('w-full'):
                            ui.label(user.username).classes('text-center my-auto grow')
                            ui.button("移出用户组", icon="person_remove",
                                      on_click=lambda user=user: remove_user(user, user_group),
                                      color='text-indigo-700') \
                                .classes("mx-auto my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")
            else:
                for user in users:
                    with ui.card().classes("h-fit w-full bg-gradient-to-br from-blue-50 to-purple-50"):
                        ui.label(user.username).classes('mx-auto')

    question_groups = manager.select_allowed_questiongroup_by_usergroup(user_group.group_name)
    with ui.card().classes("mx-auto w-full bg-gradient-to-br from-purple-50 to-blue-50"):
        with ui.column().classes('w-full grow'):
            ui.label("可见问题组（非公开）").classes('mx-auto tracking-wide text-1xl text-black')
            with ui.column().classes('w-full grow'):
                with ui.scroll_area().classes('grow'):
                    for question_group in question_groups:
                        with ui.column().classes("h-fit w-full"):
                            with ui.card().classes("h-fit w-full bg-gradient-to-br from-blue-50 to-purple-50"):
                                with ui.row().classes("my-auto w-full h-fit"):
                                    with ui.card().classes("h-12 w-3/6"):
                                        with ui.row():
                                            ui.label("问题组名").classes('font-bold')
                                            ui.label(question_group.group_name)
                                    with ui.card().classes("h-12 w-1/3"):
                                        with ui.row():
                                            ui.label("创建者").classes('font-bold')
                                            ui.label(question_group.creator_id.username)
                                    ui.button("查看", icon="manage_search", color='text-indigo-700',
                                              on_click=lambda x=question_group: on_click_question_group(x)).classes(
                                        "my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")


@ui.page("/user_groups")
async def user_groups_page():
    init_page()
    ui.label('用户组列表').classes('tracking-wide text-2xl py-8 text-black')

    def new_user_group():
        def create_user_group():
            succ, res, group_id = manager.add_usergroup(manager.get_user(app.storage.user["username"]),
                                                        app.storage.user.get("input_usergroup_name", ""))
            ui.notify(res)
            if succ:
                add_user_to_group(manager.get_user(app.storage.user["username"]), group_id)
                dialog.close()
                ui.open("/user_groups")

        with ui.dialog() as dialog, ui.card().tight().classes('w-[800px] h-fit'):
            with ui.column().classes("w-full px-[50px] py-[50px]"):
                with ui.row().classes(''):
                    ui.label("用户组组名").classes("w-[200px] my-auto")
                    ui.input("输入组名").classes("my-auto text-indigo-700") \
                        .bind_value_to(app.storage.user, "input_usergroup_name")
            ui.button("创建", on_click=lambda: create_user_group(), color='text-indigo-700') \
                .classes('w-full bg-gradient-to-br from-purple-200 to-blue-200')
        dialog.open()

    def search_user_group():
        def search_input(value):
            def apply_to_add(group):
                if not manager.get_user(app.storage.user['username']) in manager.get_users_by_groupid(group.group_name):
                    app.storage.general['加入用户组申请信息'].append(
                        [app.storage.user.get('username'), group.group_name,
                         manager.get_user(app.storage.user.get('username')).id, group.id])
                    ui.notify("申请信息发送成功，请耐心等待审核结果！")
                    print([manager.get_user(app.storage.user.get('username')).id, group.id])

            groups = manager.search_usergroup_bu_groupname(value)
            with search_result:
                search_result.clear()
                for group in groups:
                    ui.label(group.group_name).classes("mx-auto")
                    with ui.row().classes("w-full px=[20px]"):
                        ui.button("进入用户组", on_click=lambda group=group: on_click_user_group(group)
                                  , color='text-indigo-700', icon='face') \
                            .classes('bg-gradient-to-br from-purple-200 to-blue-200 grow')
                        ui.button("申请加入", on_click=lambda group=group: apply_to_add(group)
                                  , color='text-indigo-700', icon='assignment_ind') \
                            .classes('bg-gradient-to-br from-purple-200 to-blue-200 grow')

        with ui.dialog() as dialog_search, ui.card().tight().classes('w-[400px] h-[400px]'):
            ui.input("搜索用户组名", on_change=lambda e: search_input(e.value)).classes("w-full text-indigo-700")
            search_result = ui.card().classes("w-full h-full")
        dialog_search.open()
        search_input("")

    with ui.row().classes('w-full'):
        ui.button("新建用户组", on_click=lambda: new_user_group(), icon='group_add', color='text-indigo-700') \
            .classes('mr-1 h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow')
        ui.button("搜索用户组", on_click=lambda: search_user_group(), icon='search', color='text-indigo-700') \
            .classes('mr-1 h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow')

    def on_click_user_group(user_group):
        ui.open("/user_group/{}".format(user_group.id))

    user_groups = manager.select_usergroup_by_user(app.storage.user['username'])
    with ui.card().classes("mx-auto w-full bg-gradient-to-br from-purple-50 to-blue-50"):
        with ui.row().classes('w-full'):
            ui.label("用户组").classes('text-center grow')
            ui.label("创建者").classes('text-center grow')
            ui.label("操作").classes('text-center grow')

        for user_group in user_groups:
            with ui.card().classes("h-fit w-full bg-gradient-to-br from-blue-50 to-purple-50"):
                with ui.row().classes('w-full'):
                    ui.label(user_group.group_name).classes('text-center grow')
                    ui.label(user_group.creator_id.username).classes('text-center grow')
                    ui.button("进入用户组", icon="manage_search",
                              on_click=lambda user_group=user_group: on_click_user_group(user_group),
                              color='text-indigo-700') \
                        .classes("my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")

    apply_messages = app.storage.general.get('加入用户组申请信息', "none")
    if (apply_messages == 'none'):
        app.storage.general["加入用户组申请信息"] = []
    apply_messages = app.storage.general.get('加入用户组申请信息', "none")
    with ui.card().classes("mx-auto w-full bg-gradient-to-br from-purple-50 to-blue-50"):
        with ui.column().classes('w-full grow'):
            ui.label("我管理的用户组——加入申请信息列表").classes('mx-auto tracking-wide text-1xl text-black')
            with ui.row().classes('w-full'):
                ui.label("申请用户").classes('text-center grow')
                ui.label("申请加入用户组").classes('text-center grow')

            def remove_apply(apply):
                app.storage.general['加入用户组申请信息'].remove(apply)
                ui.open("/user_groups")

            def oper_apply(apply):
                add_user_to_group(apply[2], apply[3])
                remove_apply(apply)

            for apply in apply_messages:
                if manager.is_administrator(app.storage.user.get('username')) or \
                        manager.get_usergroup_by_groupid(int(apply[3]))[0].creator_id.id \
                        == manager.get_user(app.storage.user.get('username')).id:
                    with ui.card().classes("h-fit w-full bg-gradient-to-br from-blue-50 to-purple-50"):
                        with ui.row().classes('w-full'):
                            ui.label(apply[0]).classes('text-center grow')
                            ui.label(apply[1]).classes('text-center grow')
                        with ui.row().classes('w-full'):
                            ui.button("同意申请", icon="done", on_click=lambda apply=apply: oper_apply(apply),
                                      color='text-indigo-700') \
                                .classes("mx-auto my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")
                            ui.button("拒绝申请", icon="close", on_click=lambda apply=apply: remove_apply(apply),
                                      color='text-indigo-700') \
                                .classes("mx-auto my-auto h-12 bg-gradient-to-br from-purple-200 to-blue-200 grow")
